package com.example.myapplication.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.utils.net.Uri;

public class DataBaseUtil {

    private static Uri uri = Uri.parse("dataability:///com.example.myapplication.ShopDataAbility/fmall_info");

    public static String getValue(String key,Context context){
        String value = null;

        //访问本地数据库，是否存在用户信息，如果存在则加载Layout_ability_main(首页),否则加载登录页面
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);

        String[] colums = {"value"};
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo("key",key);
        try {
            ResultSet rs = dataAbilityHelper.query(uri, colums, predicates);
            //如果大于0，表示查询到数据
            if (rs.getRowCount() > 0){
                rs.goToFirstRow();
                value = rs.getString(0);
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        return value;
    }

    //将键值对存入本地数据库，存入成功返回1，失败返回0
    public static int setValue(String key,String value,Context context){
        int i = 0;
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString("key",key);
        valuesBucket.putString("value",value);
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);
        try {
            i = dataAbilityHelper.insert(uri, valuesBucket);

        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        return i;
    }

}
